//
//  HomeViewController.m
//  LoveFreshBeen
//
//  Created by 魏根 on 2016/10/15.
//  Copyright © 2016年 魏根. All rights reserved.
//



#import "HomeViewController.h"

#import "SearchController.h"

#import "ScanViewController.h"

#import "NetWorkingTool.h"

#import "HomeFocusModel.h"

#import "HMHomeScrollView.h"
#import "CyButton.h"

#import <Masonry.h>

#import <UIImageView+WebCache.h>

#import "HMHomeCell.h"

#import "HMHomeMaxCell.h"

#import <MJRefresh.h>

#import "HMHomeBottomCell.h"

#import "HMHomeCollectionViewCell.h"

#import "HMHomeFirstModel.h"

#import "HMHomeScrollView.h"

#import "BaseTabBarVC.h"

#import <POP.h>

#import <SDImageCache.h>

#import "HMHomeClickViewController.h"

#import "WebController.h"



static  NSString* reuserIdT = @"cellsmall";

static NSString* reuserIdC = @"cellcollection";

@interface HomeViewController ()<UIScrollViewDelegate,UICollectionViewDelegate,UICollectionViewDataSource,CAAnimationDelegate>

@property(nonatomic,strong)NSArray* modelArray;

@property(nonatomic,strong)NSArray* imageArray;

@property(nonatomic,weak)UIPageControl* page;

@property(nonatomic,strong)NSTimer* time;

@property(nonatomic,strong)HMHomeScrollView* scrollView;

@property(nonatomic,strong)NSArray* iconArray;

@property(nonatomic,strong)NSArray* activityArray;

@property(nonatomic,strong)NSArray* hotBuyArray;

@property(nonatomic,strong)CALayer* layer;



@end

@implementation HomeViewController



-(void)setModelArray:(NSArray *)modelArray
{
    _modelArray = modelArray;
    
    self.scrollView.modelArray = self.modelArray;

}
-(void)setIconArray:(NSArray *)iconArray
{
    
    _iconArray = iconArray;
    [self.tableView reloadData];
}
-(void)setActivityArray:(NSArray *)activityArray
{
    
    _activityArray = activityArray;
    [self.tableView reloadData];
}

-(void)setHotBuyArray:(NSArray *)hotBuyArray
{
    _hotBuyArray = hotBuyArray;
    UICollectionView* collectionView = (UICollectionView*)self.tableView.tableFooterView;
    [collectionView reloadData];

    
}
- (void)viewDidLoad {
    [super viewDidLoad];
#pragma mark----下拉刷新
    
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData:)];
    
    UIImage *image1 = [UIImage imageNamed:@"v2_pullRefresh1"];
    
    UIImage *image2 = [UIImage imageNamed:@"v2_pullRefresh2"];
    
    [header setImages:@[image1] forState:MJRefreshStateIdle];
    
    [header setImages:@[image2] forState:MJRefreshStatePulling];
    
    [header setImages:@[image1,image2] forState:MJRefreshStateRefreshing];
    
    [header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
    
    [header setTitle:@"松手开始刷新" forState:MJRefreshStatePulling];
    
    [header setTitle:@"正在刷新" forState:MJRefreshStateRefreshing];
    
    header.lastUpdatedTimeLabel.hidden = YES;
    
    self.tableView.mj_header = header;
    
    
    //在底部的FooterView中添加colletionView
    
    [self setMyUI];
    
    
     NSString* str  = [NetWorkingTool shareInstance].params[@"2"];
    
    [[NetWorkingTool shareInstance] getDatawithParam:@"2" WithUrlString:str withSuccessBlock:^(id data) {
        
//        NSLog(@"First%@",data);
        
    } withFailedBlock:^(NSError *error) {
        
        NSLog(@"%@",error);
        
    } withErrorBlock:^(NSString *message) {
        
         NSLog(@"%@",message);
        
    }];
    
    _modelArray = [[NSArray alloc]init];
    
    self.navigationController.navigationBar.translucent = NO;
    
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    
    [HomeFocusModel downLoadTheMessage:@"focus" andFinish:^(NSArray *array) {
        
        self.modelArray = array;
        
        [self.tableView reloadData];
      
    } andError:^{
        
        NSLog(@"加载focus失败");
        
        
    }];
    
    [HomeFocusModel downLoadTheMessage:@"icons" andFinish:^(NSArray *array) {
        
        self.iconArray = array;
        
    } andError:^{
        
        NSLog(@"加载icons失败");
        
    }];
    
    [HomeFocusModel downLoadTheMessage:@"activities" andFinish:^(NSArray *array) {
        self.activityArray = array;
        
    } andError:^{
        
        NSLog(@"加载activitys失败");
        
    }];
    
    [HMHomeFirstModel downLoadTheMessageFirst:@"2" andFinish:^(NSArray *array) {
        self.hotBuyArray = array;
        [self.tableView reloadData];
    } andError:^{
        NSLog(@"加载新鲜热卖数据失败");
    }];
    
    
    //   [self setMyUI];

    
}

#pragma mark--设置UI界面
-(void)setMyUI{
    
    
    self.navigationItem.titleView = [[NSBundle mainBundle] loadNibNamed:@"TitleView" owner:nil options:nil].lastObject;
    
    [self.navigationController.navigationBar setBarTintColor:[UIColor colorWithRed:254/255.0 green:211/255.0 blue:65/255.0 alpha:1]];
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[self setBtnWithTitle:@"扫一扫" imageName:@"icon_black_scancode" target:self action:@selector(scan_QR_Code)]];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:[self setBtnWithTitle:@"搜 索" imageName:@"icon_search" target:self action:@selector(search)]];
    
    
    UIScreen* screen = [UIScreen mainScreen];
    
    CGFloat imageWidth = screen.bounds.size.width;
    

    UIView* holdView = [[UIView alloc]init];
    
    self.tableView.tableHeaderView = holdView;
    
    [holdView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.width.equalTo(@(imageWidth));
        
        make.height.equalTo(@(150));
        
        
    }];
    
    
    
    
    
    HMHomeScrollView* scrollView = [[HMHomeScrollView alloc]init];
    
    scrollView.showsHorizontalScrollIndicator = NO;
   
    scrollView.showsVerticalScrollIndicator = NO;

  
//    self.tableView.tableHeaderView = scrollView;

    
    self.scrollView = scrollView;
    
    scrollView.backgroundColor = [UIColor whiteColor];
    
    scrollView.delegate = self;
    
    scrollView.pagingEnabled = YES;
    
    [self starMyTimer];
    
//        int count = (int)self.modelArray.count;
    //由于设置UI界面在下载完成之前调用,所以设置轮播器的时候必须先把站位数写出来
    int count = 5;
    
    
    scrollView.contentSize = CGSizeMake(count * imageWidth , 150);
    
      [holdView addSubview:scrollView];
    
    [scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
//        make.width.equalTo(@(imageWidth));
//        
//        make.height.equalTo(@(150));

        make.top.leading.trailing.bottom.equalTo(holdView);
        
      
    }];
    
    

    
    
    UIPageControl* page = [[UIPageControl alloc]init];
    
    self.page = page;
    
    page.numberOfPages = 5;
    
    page.tintColor = [UIColor darkGrayColor];
    
    page.currentPageIndicatorTintColor = [UIColor whiteColor];
    
    [holdView addSubview:page];
    
    [page mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(holdView);
        
        make.trailing.equalTo(holdView.mas_trailing).offset(-20);
    }];
    
    
    
    
#pragma mark-----设置footView部分
    
    UICollectionViewFlowLayout* layout = [[UICollectionViewFlowLayout alloc]init];
    
    //将collection=tablefootView必须设置实例化方法中的frame,否则tableFootview不会出现
    UICollectionView* collection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, imageWidth, [UIScreen mainScreen].bounds.size.height) collectionViewLayout:layout];
  
    self.tableView.tableFooterView = collection;
    
    
    CGFloat item = (imageWidth - 30)/2;
    
    layout.itemSize = CGSizeMake(item, item);
    
    layout.minimumLineSpacing = 5;
    
    layout.minimumInteritemSpacing = 5;
    
    layout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
    
    
    collection.bounces = NO;
    
    collection.delegate = self;
    
    collection.dataSource = self;
    
    collection.backgroundColor = [UIColor whiteColor];
    
 
    self.tableView.tableFooterView.backgroundColor = [UIColor colorWithRed:239/255.0 green:239/255.0 blue:239/255.0 alpha:1];
    
    
}

#pragma mark---------------collectionView的代理方法

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    
    return 1;
    
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.hotBuyArray.count;
    
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    //由于刷新多次,所以必须把xib的注册写入该方法中,否者会提示没有注册Xib
    UINib* nib = [UINib nibWithNibName:@"HMHomeCollectionViewCell" bundle:nil];
    
    [collectionView registerNib:nib forCellWithReuseIdentifier:reuserIdC];
    
    
    __weak HMHomeCollectionViewCell* cell1 = [collectionView dequeueReusableCellWithReuseIdentifier:reuserIdC  forIndexPath:indexPath];
    
    CGFloat imgeW = [UIScreen mainScreen].bounds.size.width/8;
    
    CGFloat imageH = 69;
    
    CGFloat imageX = 5 * imgeW;
    
    CGFloat imageY = [UIScreen mainScreen].bounds.size.height - imageH/2;
    
    CGPoint endPonit = CGPointMake(imageX, imageY);
    
    
       cell1.model = self.hotBuyArray[indexPath.item];
    
  
    
#pragma mark---购物车动画制作
    cell1.reloadBlock = ^(CGRect rect){
        
//        NSLog(@"%@",NSStringFromCGRect(cell1.frame));
        
        NSURL* url = [NSURL URLWithString:cell1.model.img];
        
        CGPoint cotrollPoint = CGPointMake(endPonit.x, CGRectGetMidY(rect));
        
        UIBezierPath* path = [UIBezierPath bezierPath];
        
        [path moveToPoint:CGPointMake(CGRectGetMidX(rect), CGRectGetMidY(rect))];
        
        [path addQuadCurveToPoint:endPonit controlPoint:cotrollPoint];
        
       _layer = [CALayer layer];
        
       
   
        [[SDWebImageManager sharedManager] downloadImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
         
            _layer.contents = (__bridge id _Nullable)(image.CGImage);
        }];
        

//        [[SDWebImageDownloader sharedDownloader] downloadImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
//            
//            NSLog(@"图片下载玩不");
//            layer.contents = (__bridge id _Nullable)(image.CGImage);
//            
//        }];
        
        
        
        _layer.frame = CGRectMake(cell1.bounds.origin.x,cell1.bounds.origin.y, cell1.frame.size.width, cell1.frame.size.width);
        
        
        [[UIApplication sharedApplication].delegate.window.layer addSublayer:_layer];
        
        CAAnimationGroup* group = [[CAAnimationGroup alloc]init];
        
        CABasicAnimation* scale = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        
        scale.removedOnCompletion = YES;
        
        scale.fromValue = @0.8;
        
        scale.toValue = @0;
        
        CAKeyframeAnimation* keyAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
        
        keyAnimation.path = path.CGPath;
        
        CABasicAnimation* rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        
        rotate.fromValue = [NSNumber numberWithInt:0];
        
        rotate.toValue = [NSNumber numberWithInt:10];
        
        rotate.removedOnCompletion = YES;
        
        group.delegate = self;
        
        group.animations = @[scale,keyAnimation,rotate];
        
        group.duration = 2;
        

        
        group.fillMode = kCAFillModeForwards;
        
        group.timingFunction =[CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionEaseIn];
        
        //该处如果选择yes则会在左上角出现选中图片,该属性意思为动画完成后是否移除动画,如果移除则不会根据key值进行判断动画类型
        group.removedOnCompletion = NO;
        
        [_layer addAnimation:group forKey:@"group"];
        
        
    };

    return cell1;


    
    
    
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    HMHomeClickViewController* home = [[HMHomeClickViewController alloc]init];
    //必须同时时设置hidesBottomBarWhenPushed 的YES和NO两个属性,否则会出现各种问题
   home.hidesBottomBarWhenPushed = YES;
    
    home.model = self.hotBuyArray[indexPath.item];
    
//    [self presentViewController:nav animated:YES completion:nil];
    
    [self.navigationController pushViewController:home animated:YES];
    
    //使用当前类调用该方法隐藏必须写该句代码,否则控制器返回时底部tabbar异常
//     self.hidesBottomBarWhenPushed = NO;
    
    
}


-(void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag
{

    
    if (anim == [_layer animationForKey:@"group"])
          {
        
              [_layer removeFromSuperlayer];
              
              _layer = nil;
              
           
              
    }
    
//        [self.layer removeAllAnimations];
        
    
        
    
    
 
    
}
//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
//    
//    NSString* reuserFoot = @"footView";
//    
//    UICollectionReusableView* footView = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:reuserFoot forIndexPath:indexPath];
//    
//    return footView;
//    
//    
//    
//
//    
//}

- (void)refreshData:(MJRefreshGifHeader *)header{

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        
        
        [self.tableView.mj_header endRefreshing];
    });
}




-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    NSInteger index = (scrollView.contentOffset.x + [UIScreen mainScreen].bounds.size.width * 0.5)/[UIScreen mainScreen].bounds.size.width;
    
    self.page.currentPage = index;
    
    
    
}

#pragma mark---------定时器
-(void)starMyTimer{
    
    NSTimer* time = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(scrollToScroll) userInfo:nil repeats:YES];
    
    
    [[NSRunLoop mainRunLoop] addTimer:time forMode:NSRunLoopCommonModes];
//    [NSRunLoop mainRunLoop]
//    self.time = time;
//    [[NSRunLoop mainRunLoop] run];
    
//        CADisplayLink* diapaly = [CADisplayLink displayLinkWithTarget:self selector:@selector(scrollToScroll)];
//        [diapaly addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
    self.time = time;
    
    
    
}
-(void)scrollToScroll{
    
   
    
    UIImageView* lastImage = [self.scrollView.subviews lastObject];
    
   
    
    CGFloat lastX = CGRectGetMaxX(lastImage.frame) - [UIScreen mainScreen].bounds.size.width;
    
    if (self.scrollView.contentOffset.x >= lastX)
    {
        
        [self.scrollView setContentOffset:CGPointZero animated:NO];
    }else
    {
        
        CGFloat realOffset = self.scrollView.contentOffset.x;
        
        realOffset += [UIScreen mainScreen].bounds.size.width;
        
        [self.scrollView setContentOffset:CGPointMake(realOffset, 0) animated:YES];
    }
    
}
-(void)cutTheTimer{
    
    [self.time invalidate];
    
    self.time = nil;
    
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
   
    [self cutTheTimer];
    
}

-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self starMyTimer];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
#pragma mark -----tableView代理发法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
    
    
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        
        return 1;
    }else
    {
        return self.activityArray.count;
    }
    
    
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    
    HMHomeCell* cell = [tableView dequeueReusableCellWithIdentifier:reuserIdT];
    
    if (indexPath.section == 0) {
        

        if (cell == nil)
        {
            cell = [[HMHomeCell alloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier:@"cellsmall"];
        }
        
        cell.modelArray = self.iconArray;
        
       return cell;
        
    }else
    {
        
        HMHomeMaxCell* cell1 = [tableView dequeueReusableCellWithIdentifier:@"cellmax"];
        if (cell1 == nil) {
            
           cell1 = [[HMHomeMaxCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellmax"];
           
            
        }
        
         cell1.model = self.activityArray[indexPath.row];
    
        
        return cell1;
    }
  
    
}

#pragma mark -----行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0)
    {
        return 80;
    }else
    {
        return 150;
        
    }
    
}
-(void)giveMeShoppingCenter:(CGSize)size
{
//    UITabBar* bottomBar  = self.tabBarController.tabBar;
//    

//    
//    [bottomBar.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//        
//        if ([obj isKindOfClass:NSClassFromString(@"UITabBarButton")])
//        {
//            
//            
//           [obj.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
//               
//               NSLog(@"222222222%@",NSStringFromCGRect(obj.frame));
//               
//               if ([obj isKindOfClass:NSClassFromString(@"UITabBarSwappableImageView")]) {
//                   
//                   CGPoint ok = obj.center;
//                   
//                   NSLog(@"1111111111111111111%f,  %f",ok.x,ok.y);
   
//               }
//           }];
//        }
//        }];

    
//    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
//    
//    UIImage* image = UIGraphicsGetImageFromCurrentImageContext();
//    
//    UIGraphicsEndImageContext();
//    
//    POPSpringAnimation* pop = [POPSpringAnimation animationWithPropertyNamed:kPOPLayerPosition];
//    
//    NSLog(@"%@",image);
//    
//    pop.springSpeed = 10;
//    
//    pop.springBounciness = 10;
//    
//    pop.toValue = [NSValue valueWithCGPoint:CGPointMake(0, 0)];
//    
//    UIImageView* ima = [[UIImageView alloc]initWithImage:image];
//    
//    ima.frame = CGRectMake(0, 0, 172, 97);
//    
//    ima.backgroundColor = [UIColor redColor];
//    
//    self.tableView.tableFooterView=ima;
//    
////    [ima pop_addAnimation:pop forKey:nil];
//    
//    
//    
//    NSLog(@"111");
    
    



}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WebController *vc = [[WebController alloc] init];
    
    HomeFocusModel *model = self.modelArray[indexPath.row];
    
    vc.model = model;
    
    vc.hidesBottomBarWhenPushed = YES;
    
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - Search

- (void)search {
    
    SearchController *searchVC = [[SearchController alloc]init];
    
    [self.navigationController pushViewController:searchVC animated:YES];
}


#pragma mark - Scan QR Code


- (void)scan_QR_Code {
    
    ScanViewController* scanVC = [[ScanViewController alloc] init];
    [self.navigationController pushViewController:scanVC animated:YES];
}


#pragma mark - Set scanBtn & searchBtn
- (CyButton *)setBtnWithTitle:(NSString *)title imageName:(NSString *)imageName target:(id)target action:(SEL)action {
    CyButton *btn = [[CyButton alloc]initWithFrame:CGRectMake(0, 0, 30, 40)];
    
    [btn setImage:[[UIImage imageNamed:imageName] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    
    [btn setTitle:title forState:UIControlStateNormal];
    
    [btn addTarget:self action:action forControlEvents:UIControlEventTouchUpInside];
    btn.titleLabel.font = [UIFont systemFontOfSize:9];
    
    [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    return btn;
}



-(void)viewWillAppear:(BOOL)animated{
    UICollectionView* collectionView = (UICollectionView*)self.tableView.tableFooterView;
    [collectionView reloadData];
    
}

@end



